from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.views.generic import TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Q, Count, Sum, F
from django.http import HttpResponse
from django.utils import timezone
from datetime import datetime, timedelta
from docx import Document
from io import BytesIO
import logging

from core.models.student import Student
from core.models.classinfo import ClassInfo
from core.models.semester import Semester
from core.models.student_comment import StudentComment
from core.models.grade import Grade
from core.models.school_schedule import SchoolSchedule
from core.models.homework import Homework
from core.models.homework_submission import HomeworkSubmission
from core.models.daily_attendance import DailyAttendance
from core.models.teacher_subject_assignment import TeacherSubjectAssignment
from .utils import get_user_subject_classes
# 配置日志
logger = logging.getLogger(__name__)


@login_required
def student_comment_management(request):
    """
    学生评语管理视图
    功能: 显示班主任所带班级的学生列表及其评语信息，支持学期筛选
    参数: request - HTTP请求对象
    返回: 渲染的学生评语管理页面
    """
    # 获取当前用户作为班主任的班级
    teacher_classes = ClassInfo.objects.filter(homeroom_teacher=request.user)
    
    # 获取当前学期
    current_semester = Semester.objects.filter(is_current=True).first()
    
    # 如果没有当前学期，获取最近的学期
    if not current_semester:
        current_semester = Semester.objects.order_by('-start_date').first()
    
    # 处理学期选择
    semester_id = request.GET.get('semester')
    if semester_id:
        try:
            selected_semester = Semester.objects.get(id=semester_id)
        except Semester.DoesNotExist:
            selected_semester = current_semester
    else:
        selected_semester = current_semester
    
    # 获取所有学期供选择
    all_semesters = Semester.objects.order_by('-start_date')
    
    # 存储班级和学生信息
    class_students = []
    
    for class_info in teacher_classes:
        # 获取班级中的学生
        students = Student.objects.filter(classes=class_info)
        
        # 为每个学生获取对应的评语
        student_comments = {}
        for student in students:
            comment = StudentComment.objects.filter(
                student=student,
                class_info=class_info,
                semester=selected_semester
            ).first()
            student_comments[student.id] = comment
        
        class_students.append({
            'class_info': class_info,
            'students': students,
            'student_comments': student_comments
        })
    
    context = {
        'class_students': class_students,
        'all_semesters': all_semesters,
        'selected_semester': selected_semester
    }
    
    return render(request, 'classmanage/student_comment_management.html', context)

@login_required
def student_comment_edit(request, student_id, class_id, semester_id):
    """
    编辑学生评语视图
    功能: 允许班主任编辑特定学生的评语
    参数:
        request - HTTP请求对象
        student_id - 学生ID
        class_id - 班级ID
        semester_id - 学期ID
    返回: 渲染的编辑页面或重定向到评语管理页面
    """
    student = get_object_or_404(Student, id=student_id)
    class_info = get_object_or_404(ClassInfo, id=class_id)
    semester = get_object_or_404(Semester, id=semester_id)
    
    # 检查当前用户是否是该班级的班主任
    if request.user != class_info.homeroom_teacher:
        messages.error(request, '您没有权限编辑此学生的评语。')
        return redirect('core:student_comment_management')
    
    # 获取或创建评语
    comment, created = StudentComment.objects.get_or_create(
        student=student,
        class_info=class_info,
        semester=semester,
        defaults={'content': ''}
    )
    
    if request.method == 'POST':
        content = request.POST.get('content', '')
        comment.content = content
        comment.save()
        messages.success(request, '评语已保存成功。')
        return redirect('core:student_comment_management')
    
    context = {
        'student': student,
        'class_info': class_info,
        'semester': semester,
        'comment': comment
    }
    return render(request, 'classmanage/student_comment_edit.html', context)

class TeacherDashboardView(LoginRequiredMixin, TemplateView):
    template_name = 'class_teacher/dashboard.html'
    login_url = '/login/'
    redirect_field_name = 'redirect_to'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        request = self.request
        try:
            # 获取当前教师所带的班级（包括班主任和科任教师）
            logger.info(f"用户 {request.user.username} 正在查询所带班级")
            # 暂时只查询班主任班级，测试是否有数据
            teacher_classes = get_user_subject_classes(request.user)
            logger.info(f"查询到的班级数量: {teacher_classes.count()}")
            # 检查是否有班级
            if not teacher_classes.exists():
                logger.warning(f"用户 {request.user.username} 没有关联任何班级")
                context['no_classes'] = True
                return context
                
            class_ids = [cls.id for cls in teacher_classes]

            # 优化查询: 一次性获取所有班级的学生数量
            class_student_counts = dict(
                Student.objects.filter(classes__in=teacher_classes)
                .values('classes__id')
                .annotate(count=Count('id'))
                .values_list('classes__id', 'count')
            )

            # 填充没有学生的班级
            for cls in teacher_classes:
                if cls.id not in class_student_counts:
                    class_student_counts[cls.id] = 0

            # 获取最近7天的考勤统计
            seven_days_ago = timezone.now().date() - timedelta(days=7)
            logger.info(f"查询考勤数据: 日期范围从 {seven_days_ago} 到 {timezone.now().date()}")
            logger.info(f"涉及班级数量: {teacher_classes.count()}")

            attendance_stats = DailyAttendance.objects.filter(
                student__classes__in=teacher_classes,
                date__gte=seven_days_ago
            ).values('date').annotate(
                present=Count('id', filter=Q(morning_attendance=True) | Q(afternoon_attendance=True) | Q(evening_attendance=True)),
                absent=Count('id', filter=Q(morning_attendance=False) & Q(afternoon_attendance=False) & Q(evening_attendance=False))
            ).order_by('date')

            logger.info(f"查询到的考勤记录数量: {attendance_stats.count()}")

            # 生成最近7天的日期标签
            all_dates = [(seven_days_ago + timedelta(days=i)).strftime('%Y-%m-%d') for i in range(7)]
            date_to_present = {item['date'].strftime('%Y-%m-%d'): item['present'] for item in attendance_stats}
            date_to_absent = {item['date'].strftime('%Y-%m-%d'): item['absent'] for item in attendance_stats}

            # 确保每个日期都有数据点，即使为0
            attendance_labels = all_dates
            present_data = [date_to_present.get(date, 0) for date in all_dates]
            absent_data = [date_to_absent.get(date, 0) for date in all_dates]

            logger.info(f"处理后的考勤数据 - 标签: {attendance_labels}")
            logger.info(f"处理后的考勤数据 - 出勤: {present_data}")
            logger.info(f"处理后的考勤数据 - 缺勤: {absent_data}")

            # 获取未提交作业统计 (前5个)
            homework_stats = HomeworkSubmission.objects.filter(
                homework__class_subject__class_id__in=class_ids,
                status='unsubmitted'
            ).values('homework__content').annotate(
                count=Count('id')
            ).order_by('-count')[:5]

            # 处理作业数据为图表所需格式
            homework_labels = []
            homework_data = []
            for item in homework_stats:
                content = item['homework__content']
                homework_labels.append(content[:20] + '...' if len(content) > 20 else content)
                homework_data.append(item['count'])

            # 添加作业数据默认值
            if not homework_labels:
                homework_labels = ['暂无未提交作业']
                homework_data = [0]

            # 计算学生总数
            total_students = sum(class_student_counts.values())
            
            # 计算未提交作业总数
            total_unsubmitted_homeworks = sum(item['count'] for item in homework_stats)
            
            context.update({
                'teacher_classes': teacher_classes,
                'class_student_counts': class_student_counts,
                'attendance_stats': attendance_stats,
                'homework_stats': homework_stats,
                'total_students': total_students,
                'total_unsubmitted_homeworks': total_unsubmitted_homeworks,
                'attendance_labels': attendance_labels,
                'present_data': present_data,
                'absent_data': absent_data,
                'homework_labels': homework_labels,
                'homework_data': homework_data,
            })
            logger.info(f"Teacher dashboard data loaded successfully for user {request.user.username}")
        except Exception as e:
            logger.error(f"Error loading teacher dashboard data: {str(e)}")
            messages.error(request, '加载仪表盘数据时发生错误，请稍后重试。')

        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context)


@login_required
def export_comments_to_word(request):
    """
    导出评语到Word文档视图
    功能: 将选中学生的评语导出为Word文档
    参数: request - HTTP请求对象
    返回: Word文档下载响应或重定向
    """
    if request.method == 'POST':
        student_ids = request.POST.getlist('student_ids[]')
        semester_id = request.POST.get('semester_id')

        if not student_ids:
            messages.error(request, '请先选择要导出的学生。')
            return redirect('core:student_comment_management')
        
        # 此处为导出功能的部分代码，完整实现需要补充

